﻿/**
 * 消息弹出框相关接口
 * */
Ext.namespace('Wo.MainFrame');

/**
 * 在内容主tab面板中，最多可以打开的tab数量
 * */
Wo.MainFrame.MaxTabs = 10;

//在右侧tab中，根据菜单树节点的信息获取其对应的页面
Wo.MainFrame.getTreeTabContentPanel = function (tab, menuId) {
    for (var i = 0; i < tab.items.getCount(); i++) {
        var id = 'woGridPanel_' + tab.items.item(i).getId();
        if (id == menuId) {
            return tab.items.item(i);
        }
    }
};

Wo.MainFrame.showLogin = function () {
    // 表单中的字段定义
    var fields = [{
        fieldLabel: '用户',
        name: 'user',
        allowBlank: false,
        width: 100
    }, {
        fieldLabel: '密码',
        name: 'password',
        inputType: 'password',
        width: 100,
        allowBlank: false,
        listeners: {
            specialkey: function (field, e) {
                if (e.getKey() == e.ENTER) {
                    submitLogin();
                }
            }
        }
    }];
    var login = new Ext.FormPanel({
        id: 'woLoginForm',
        bodyStyle: 'padding-top:30px;',
        url: 'authentication',
        frame: true,
        // title : 'Please Login',
        plain: true,
        labelWidth: 80,
        labelAlign: 'right',
        defaultType: 'textfield',
        monitorValid: true,
        region: 'center',
        // Specific attributes for the text fields for username
        // / password.
        // The "name" attribute defines the name of variables
        // sent to the
        // server.
        items: fields,
        // All the magic happens after the user clicks the
        // button
        buttons: [{
            text: '登录',
            formBind: true,
            // Function that fires when user clicks the button
            handler: function () {
                submitLogin();
            }
        }]
    });
    var topPl = {
        region: 'west',
        width: 200,
        height: 150,
        items: [{
            xtype: 'box',
            autoEl: {
                tag: 'img',
                src: 'image/logo_login.png',
                width: '100%',
                height: '100%'
            }
        }]
    };
    // This just creates a window to wrap the login form.
    // The login object is passed to the items collection.
    var win = new Ext.Window({
        // bodyStyle : '',
        layout: 'border',
        title: '请登录...',
        width: 430,
        height: 200,
        closable: false,
        resizable: false,
        plain: true,
        border: false,
        items: [login, topPl]
    });
    win.show();
    // 提交方法定义
    var submitLogin = function () {
        Ext.getCmp('woLoginForm').getForm().submit({
            method: 'POST',
            waitTitle: '等待提示',
            waitMsg: '正在提交数据，请稍后',
            success: function (json) {
                window.location = '';
                // Ext.getCmp ('woMenuTreePanel').setTitle ('欢迎您，' + json.content.staffNames + '【' + json.content.staffDeptNames + '】！');
//				var rootNode = Ext.getCmp('woMenuTreePanel').getRootNode();
//				console.log (rootNode.id);
//				for (var i = 0; i < rootNode.childNodes.length; i ++) {
//					// rootNode.childNodes[i].remove ();
//				}
//				// rootNode.removeAll(false);
//				Ext.getCmp('woMenuTreePanel').load (rootNode);
                // rootNode.expand();
                // win.close();
            },
            failure: function (form, action) {
                var obj;
                try {
                    obj = Ext.util.JSON.decode(action.response.responseText);
                } catch (e) {
                    Wo.MsgBox.warn('未知异常！');
                    return;
                }
                if (action.failureType != 'server') {
                    Wo.MsgBox.warn(obj.error);
                } else {
                    Wo.MsgBox.warn(obj.msg);
                }
                Ext.getCmp('woLoginForm').getForm().reset();
            }
        });
    };
};

/** ========================= main entry ====================== */
/**
 * Invoking onReady method of Ext, this is the main entry of our pages.
 */
Ext.onReady(function () {
    Ext.QuickTips.init();
    Ext.BLANK_IMAGE_URL = "js/ext/resources/images/default/s.gif";
    new Ext.Viewport({
        layout: 'border',
        enableTablScroll: false,
        items: [{
            xtype: 'panel',
            title: woWelcome,
            region: 'north',
            tools: [{
                id: 'close',
                text: '退出',
                handler: function () {
                    Wo.MsgBox.confirm('确定要退出吗？', function () {
                        Wo.Ajax.request({// ajax请求（POST），将选中的菜单ID传入
                            url: 'logout',
                            woSuccess: function () {
                                window.location = "";
                            }
                        });
                    });
                }
            }],
        }, {
            id: 'woContentTabPanel',
            xtype: 'tabpanel',
            enableTabScroll: true,
            border: true,
            resizeTabs: true,
            // minTabWidth: 75,
            region: 'center',
            frame: true
        }, {
            id: 'woMenuTreePanel',
            title: '菜单',
            xtype: 'treepanel',
            autoScroll: true,
            enableDD: true,
            collapsible: true,
            region: 'west',
            // url需要的json格式参考：
            // http://docs.sencha.com/extjs/3.4.0/#!/api/Ext.tree.TreeNode的config配置
            loader: new Ext.tree.TreeLoader({
                dataUrl: 'getChildren',
                nodeParameter: 'parentId',
                listeners: {
                    load: function (treeLoader, node, response) {
                        var reponseJsonData;
                        try {
                            reponseJsonData = Ext.util.JSON.decode(response.responseText);
                        } catch (e) {
                            Wo.MsgBox.error('加载失败，' + e.name + ":" + e.message);
                            return;
                        }
                        if (reponseJsonData.success == false) {
                            Wo.MainFrame.showLogin();
                        }
                    }
                }
            }),
            width: 200,
            rootVisible: false,
            root: {
                id: 'woMenuRoot',
                xtype: 'treenode',
                text: 'Root Node',
                expanded: true
            },
            listeners: {
                'click': function (node, e) {
                    if (node.attributes.leaf) {
                        var tab = Ext.getCmp('woContentTabPanel');
                        var pl = Wo.MainFrame.getTreeTabContentPanel(tab, node.attributes.id);
                        if (!pl) {
                            if (tab.items.getCount() >= Wo.MainFrame.MaxTabs) {
                                Wo.MsgBox.warn('最多只能打开' + Wo.MainFrame.MaxTabs + '个面板哟，您可以关闭部分不需要的面板，然后再重试！');
                                return;
                            }
                            var panelClass = node.attributes.panelClass;
                            if (Ext.isEmpty(panelClass)) {
                                panelClass = 'Ext.Panel';
                            } else {
                            	Wo.loadJsByClass(panelClass);
                            }
                            pl = eval('new ' + panelClass + '({title:"' + node.attributes.text + '", id:"' + node.attributes.id + '", closable : true})');
                            tab.add(pl);
                        }
                        tab.activate(pl);
                    }
                }
            }
        }]
    });
    // Wo.MainFrame.showLogin();
});